import React, { useState } from 'react';
import { message } from 'antd';
import { useSetState } from 'ahooks';
import moment from 'moment';
import _ from 'lodash';

import { HttpCode } from '#/utils/contacts.js';
import { Header } from '../components';
import {
  PredictivePower,
  MaintenanceSchedule,
  MaintenanceScheduleModal,
  YearlyMaintenancePlans,
} from './components';
import type {
  IProps,
  IOrginDealElementOptions,
  IStationsDataType,
  IFormValue,
  IDealElementOptions,
  IIsErrorType,
  IIsLoadingType,
  IPostPredictivePowerDataParamsType,
  IPredictivePowerDataType,
  IDataListType,
  IMaintenancePlanModalType,
} from '../type';
import { INuclearPowerStatusType } from '../type';
import {
  queryProvinceList,
  postSaveTendingPlan,
  postQueryPowerForecastCurve,
  postQueryTendingPlanList,
  getQueryCapacityByStationId,
} from '../services.js';
import {
  formatJson,
  dealDataSource,
  pointConvert,
  enumerateDaysBetweenDates,
  TIME_ENUM,
} from '../tool';
import styles from './index.less';
import { TABLECOLUMNS } from '../dictionary';
import { export_json_to_excel } from '@/utils/fileExport.js';

export default (props: IProps) => {
  const { power, buttonPermissions, allKeys } = props;
  const canEport =
    buttonPermissions.findIndex((item: any) => item.menuCode === 'PowerForecastExport') > -1;
  const [visible, setVisible] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<IIsLoadingType>({
    predictivePowerIsLoading: true,
    maintenanceScheduleIsLoading: true,
  });
  const [isError, setIsError] = useSetState<IIsErrorType>({
    predictivePowerIsError: false,
    maintenanceScheduleIsError: false,
  });
  const [provinceOptions, setProvinceOptions] = useState<IDealElementOptions[]>([]); // 省份数据
  const [allStationData, setAllStationData] = useSetState<IStationsDataType>({
    dealElementOptions: [],
    dealElementModalOptions: [],
    allKeys,
  }); // 交易单元列表
  const [formValue, setFormValue] = useSetState<IFormValue>({});
  const [predictivePowerData, setPredictivePowerData] = useState<IPredictivePowerDataType>();
  const [maintenanceScheduleData, setMaintenanceScheduleData] = useState<IDataListType[]>([]);
  const [capacity, setCapacity] = useState<number>();
  const [nuclearPowerStatus, setNuclearPowerStatus] = useState<INuclearPowerStatusType>(
    INuclearPowerStatusType.AFTER,
  );

  React.useEffect(() => {
    defaultRequest();
  }, []);

  // 改变省份
  const onChangeProvince = (params: IFormValue, children: any) => {
    setAllStationData({
      dealElementOptions: children,
    });
    setFormValue(params);
  };

  // 预测功率
  const getPredictivePowerData = async (params: IPostPredictivePowerDataParamsType) => {
    setIsLoading({
      predictivePowerIsLoading: true,
    });

    const res = await postQueryPowerForecastCurve(params);
    if (res && res?.statusCode === HttpCode.SUCCESS) {
      setPredictivePowerData(res?.data);
      setIsError({
        predictivePowerIsError: false,
      });
    } else {
      setIsError({
        predictivePowerIsError: true,
      });
      message.error(res?.message || '系统异常');
    }
    setNuclearPowerStatus(params?.valueType || INuclearPowerStatusType.AFTER);
    setIsLoading({
      predictivePowerIsLoading: false,
    });
  };

  // 查询交易单元装机容量
  const queryCapacityByStationId = async (stationId: string) => {
    const res = await getQueryCapacityByStationId(stationId);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      return res?.data;
    } else {
      message.error(res?.message || '系统异常');
    }
  };

  // 检修计划表
  const getPostMaintenanceScheduleData = async (params: IFormValue) => {
    setIsLoading({
      maintenanceScheduleIsLoading: true,
    });
    const res = await postQueryTendingPlanList({
      ...params,
      stationIdList: [params?.stationId as string],
    });
    if (res && res?.statusCode === HttpCode.SUCCESS) {
      setMaintenanceScheduleData(res?.data || []);
      setIsError({
        maintenanceScheduleIsError: false,
      });
    } else {
      setIsError({
        maintenanceScheduleIsError: true,
      });
      message.error(res?.message || '系统异常');
    }
    setIsLoading({
      maintenanceScheduleIsLoading: false,
    });
  };

  // 搜索数据
  const onSearch = async (params: IFormValue) => {
    const _postPredictivePowerDataParams: any = {
      ...params,
      valueType: INuclearPowerStatusType.AFTER,
    };
    setFormValue(params);
    await getPredictivePowerData(_postPredictivePowerDataParams);
    await getPostMaintenanceScheduleData(params);
    const _capacity: number = await queryCapacityByStationId(params.stationId as string);
    setCapacity(_capacity);
  };

  // 新增/编辑检修计划
  const onEditMaintenanceSchedule = async (
    record?: IDataListType,
    maintenancePlanModalType?: IMaintenancePlanModalType,
    onReview?: any,
  ) => {
    await MaintenanceScheduleModal.show({
      record,
      maintenancePlanModalType,
      allStationData: allStationData?.dealElementOptions || [],
      queryCapacityByStationId,
      onSubmit: async (data: IDataListType) => {
        const res = await postSaveTendingPlan(data);
        if (res && res?.statusCode === HttpCode.SUCCESS) {
          onReview && (await onReview());
          await onSearch(formValue);
        }
        return res;
      },
    });
  };

  // 关闭弹框
  const onClose = () => {
    setVisible(false);
  };

  // 预览全年检修计划
  const previewYearlyPlans = () => {
    setVisible(true);
  };
  const defaultRequest = async () => {
    const temp = power?.[0];
    const stationOptions: any = _.flatten(temp?.children?.map((t: any) => t.children));
    const _power = power.map((t: any) => ({
      ...t,
      children: _.flatten(t.children?.map((t: any) => t.children)),
    }));

    setProvinceOptions(_power);
    setAllStationData({
      dealElementOptions: stationOptions,
      dealElementModalOptions: power,
    });
    const _params: IFormValue = {
      startDate: moment().add(2, 'day').format('YYYY-MM-DD'),
      endDate: moment().add(5, 'day').format('YYYY-MM-DD'),
      marketId: temp?.marketId,
      provinceId: temp?.provinceId,
      stationId: stationOptions[0]?.value,
    };
    await onSearch(_params);
  };

  // 处理影响容量数据
  const getEffectCapacity = () => {
    const POINTER_NUM = TIME_ENUM(96);
    const _maintenanceScheduleData = maintenanceScheduleData.filter((item) => item.planState !== 1);
    _maintenanceScheduleData.reverse();
    const dateObjList = _maintenanceScheduleData.map((item) => {
      const startNode =
        item.startDate && item?.startTime
          ? moment(`${item.startDate} ${item?.startTime}`).format('HHmm') === '0000'
            ? moment(`${item.startDate} ${item?.startTime}`)
                .subtract(1, 'day')
                .format('YYYYMMDD 2400')
            : moment(`${item.startDate} ${item?.startTime}`).format('YYYYMMDD HHmm')
          : '';
      const endNode =
        item.endDate && item?.endTime
          ? moment(`${item.endDate} ${item?.endTime}`).format('HHmm') === '0000'
            ? moment(`${item.endDate} ${item?.endTime}`).subtract(1, 'day').format('YYYYMMDD 2400')
            : moment(`${item.endDate} ${item?.endTime}`).format('YYYYMMDD HHmm')
          : '';
      return {
        startNode,
        endNode,
        value: item?.effectCapacity,
      };
    });
    let XAXIS: any = [];
    const dateList = enumerateDaysBetweenDates(formValue.startDate, formValue.endDate);
    dateList.forEach((item) => {
      const arr = Array.from(
        { length: 96 },
        (v, j) => `${moment(item).format('YYYYMMDD')} ${POINTER_NUM[j]}`,
      );
      XAXIS = [...XAXIS, ...arr];
    });
    let dataTwo: any = Array.from({ length: XAXIS.length }, (v, j) => undefined);
    dateObjList.forEach((i) => {
      const startIndex =
        XAXIS.findIndex((j: any) => j === i.startNode) === -1
          ? 0
          : XAXIS.findIndex((j: any) => j === i.startNode);
      const endIndex =
        XAXIS.findIndex((j: any) => j === i.endNode) === -1
          ? XAXIS.length - 1
          : XAXIS.findIndex((j: any) => j === i.endNode);
      dataTwo = dataTwo.map((x: any, y: any) => {
        if (y >= startIndex && y <= endIndex) {
          return i.value;
        } else {
          return x;
        }
      });
    });
    return dataTwo;
  };

  // 导出检修计划表
  const exportMaintenancePlan = async () => {
    // if (!maintenanceScheduleData.length) return;
    if (!canEport) {
      return message.info('请联系管理员获取相关权限');
    }
    // 请求核减前后数据
    const _params = {
      ...formValue,
      valueType: INuclearPowerStatusType.BEFORE,
      stationId: formValue.stationId as string,
    };
    let beforeData, afterData;
    const [resBefore, resAfter] = await Promise.all([
      postQueryPowerForecastCurve({ ..._params, valueType: INuclearPowerStatusType.BEFORE }),
      postQueryPowerForecastCurve({ ..._params, valueType: INuclearPowerStatusType.AFTER }),
    ]);
    if (resBefore?.statusCode === HttpCode.SUCCESS) {
      beforeData = resBefore.data;
    } else {
      return message.error('导出数据失败');
    }
    if (resAfter?.statusCode === HttpCode.SUCCESS) {
      afterData = resAfter.data;
    } else {
      return message.error('导出数据失败');
    }

    const data: any = [];
    const dataTwo = getEffectCapacity();
    // 表单选择的所有日期 精确到时点
    const columns: any = [];
    const POINTER_NUM = TIME_ENUM(96);
    Array.from(
      { length: moment(formValue.endDate).diff(formValue.startDate, 'day') + 1 },
      (_, i) => {
        POINTER_NUM.forEach((v) => {
          columns.push(
            `${moment(moment(formValue.startDate).add(i, 'd')).format('YYYYMMDD')} ${v}`,
          );
        });
      },
    );

    const dataMap: any = {
      核减前: beforeData,
      核减后: afterData,
    };
    ['核减前', '核减后'].forEach((item, index) => {
      const startIndex = data.length;
      data.push([item]);
      data.push(['时间']);
      data.push(['装机容量']);
      Object.keys(dataMap[item]).forEach((t) => {
        data.push([t]);
      });
      data.push(['影响容量']);

      const dataArr: any = [];
      Object.values(dataMap[item]).forEach((t: any) => {
        const obj: any = {};
        Object.entries(t)
          .sort((a: any, b: any) => (moment(a[0]) > moment(b[0]) ? 1 : -1))
          .forEach((_t: any, _i) => {
            _t[1].map((x: any, xIndex: number) => {
              obj[`${moment(_t[0]).format('YYYYMMDD')} ${pointConvert(xIndex + 1)}`] = x;
            });
          });
        dataArr.push(obj);
      });

      columns.map((t: any, i: number) => {
        data[0 + startIndex].push('');
        data[1 + startIndex].push(t);
        data[2 + startIndex].push(capacity);
        dataArr.forEach((k: any, idx: number) => {
          data[3 + idx + startIndex].push(k[t] || '-');
        });
        data[data.length - 1].push(dataTwo[i] || '-');
      });
    });

    data.push(['检修计划表']);
    data.push([]);
    const filterVal = TABLECOLUMNS.map((t) => {
      data[data.length - 1].push(t.header);
      return t.key;
    });

    //检修计划数据
    const temp = dealDataSource(maintenanceScheduleData);

    data.push(...formatJson(filterVal, temp));

    const filename =
      '市场化运维 ' +
      allStationData.dealElementOptions.find((t: any) => t.key === formValue?.stationId)?.label;
    const params: any = {
      header: data[0],
      data: data.splice(1),
      filename,
    };
    export_json_to_excel(params);
  };
  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div className={styles.header}>
          <Header
            values={formValue}
            defaultRequest={defaultRequest}
            provinceOptions={provinceOptions}
            dealElementOptions={allStationData?.dealElementOptions}
            onSearch={onSearch}
            onChangeProvince={onChangeProvince}
            onAdd={onEditMaintenanceSchedule}
            previewYearlyPlans={previewYearlyPlans}
            exportMaintenancePlan={exportMaintenancePlan}
            canEport={!canEport}
          />
        </div>
        <div className={styles.main}>
          <div className={styles.detail}>
            <div className={styles.predictivePower}>
              <PredictivePower
                formValue={formValue}
                loading={
                  isLoading.predictivePowerIsLoading || isLoading.maintenanceScheduleIsLoading
                }
                error={isError.predictivePowerIsError || isError.maintenanceScheduleIsError}
                data={{
                  predictivePowerData,
                  maintenanceScheduleData,
                }}
                onSearch={getPredictivePowerData}
                capacity={capacity}
                nuclearPowerStatus={nuclearPowerStatus}
              />
            </div>
            <div className={styles.maintenanceSchedule}>
              <MaintenanceSchedule
                loading={isLoading.maintenanceScheduleIsLoading}
                error={isError.maintenanceScheduleIsError}
                data={maintenanceScheduleData}
                onEdit={onEditMaintenanceSchedule}
              />
            </div>
          </div>
        </div>
      </div>
      <YearlyMaintenancePlans
        visible={visible}
        onClose={onClose}
        allStationData={allStationData}
        onEdit={onEditMaintenanceSchedule}
        buttonPermissions={buttonPermissions}
      />
    </div>
  );
};
